window.onload = function(){
    //先实现点击切图的效果
    let prev = document.getElementById('prev');
    let next = document.getElementById('next');
    let list = document.getElementById('list');
    let container = document.getElementById('container');

    //切图的原理 其实就是让 list 下面的元素移动，而显示的是固定的 从0开始的那个地方
    function animate(offset){
        //先获取当前的偏移量
        let cur = parseInt(list.style.left)
        let newLeft = cur + offset;
        list.style.left = newLeft + "px";
        if(newLeft < -3000){
            list.style.left = -600 + "px";
        }
        if(newLeft > -600){
            list.style.left = -3000 + "px";
        }
    }
    
    prev.onclick = function(){
        //设置index
        index = index -1;
        if(index < 1){
            index = 5;
        }
        buttonShow();
        animate(600);
    }
    next.onclick = function(){
        index = index + 1;
        if(index > 5){
            index = 1;
        }
        buttonShow();
        animate(-600);
    }

    //以下实现 轮播的自动切换
    //刚开始想用 闭包来封装 计时器，最后发现需要使用一个全局变量
    let timer;
    function autoChange(){
        timer = setInterval(function(){
            next.onclick();
        }, 2000)   
    }

    autoChange();

    //清除计时器
    function stop(){
        clearInterval(timer);
    }
    
    container.onmouseover = stop;
    container.onmouseout = autoChange;

    //以下处理按钮的样式
    let buttons = document.getElementById('buttons').getElementsByTagName('span');
    let index = 1;

    //设置点的显示
    function buttonShow(){
        //清除之间的样式
        for(let i=0; i<buttons.length; i++){
            if(buttons[i].className === "on"){
                buttons[i].className = "";
            }
        }
        buttons[index-1].className = "on";
    }

    //给每个小圆点添加点击事件
    for(let i=0; i<buttons.length; i++){
        buttons[i].onclick = function(){
            let absoluteIndex = parseInt(this.getAttribute('index'));
            let offset = 600 * (index - absoluteIndex);
            animate(offset);
            index = absoluteIndex;
            buttonShow();
        }
    }
}